#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/cmsi/send_sms.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import json, base64
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, ListField, DefaultBooleanField
from .toolkit import configs, tools

class SendSms(Component, SetupConfMixin):
    """
    apiLabel 发送短信
    apiMethod POST
    
    ### 功能描述
    
    发送短信
    
    ### 请求参数
    
    {{ common_args_desc }}
    
    #### 接口参数
    
    | 字段               |  类型      | 必选   |  描述      |
    |--------------------|------------|--------|------------|
    | receiver           |  string    | 否     | 短信接收者，包含接收者电话号码，多个以逗号分隔，若receiver、receiver__username同时存在，以receiver为准 |
    | receiver__username |  string    | 否     | 短信接收者，包含用户名，用户需在蓝鲸平台注册，多个以逗号分隔，若receiver、receiver__username同时存在，以receiver为准 |
    | content            |  string    | 是     | 短信内容 |
    | is_content_base64  |  bool      | 否     | 消息内容是否base64编码，默认False，不编码，请使用base64.b64encode方法编码 |
    
    ### 请求参数示例
    
    ```python
    {
        "app_code": "esb_test",
        "app_secret": "xxx",
        "bk_token": "xxx",
        "receiver": "1234567890",
        "receiver__username": "admin",
        "content": "Welcome to Blueking",
    }
    ```
    
    ### 返回结果示例
    
    ```python
    {
        "result": true,
        "code": "00",
        "message": "短信发送成功。",
    }
    ```
    """
    sys_name = configs.SYSTEM_NAME
    host = configs.host
    contact_way = 'phone'

    class Form(BaseComponentForm):
        receiver = ListField(label=u'短信接收人', required=False)
        receiver__username = ListField(label=u'短信接收人', required=False)
        content = forms.CharField(label=u'消息内容', required=True)
        is_content_base64 = DefaultBooleanField(label=u'内容是否base64编码', default=False, required=False)

        def decode_content(self, content, is_content_base64):
            if is_content_base64:
                try:
                    content = base64.b64decode(content)
                except:
                    pass

            return content

        def clean(self):
            data = self.cleaned_data
            if data['receiver']:
                data['receiver__username'] = None
            data['content'] = self.decode_content(data['content'], data['is_content_base64'])
            return data

    def handle(self):
        self.qcloud_app_id = getattr(self, 'qcloud_app_id', '') or getattr(configs, 'qcloud_app_id', '')
        self.qcloud_app_key = getattr(self, 'qcloud_app_key', '') or getattr(configs, 'qcloud_app_key', '')
        self.dest_url = getattr(self, 'dest_url', '') or getattr(configs, 'send_sms_dest_url', '')
        data = self.request.kwargs
        if data['receiver']:
            tools.validate_receiver(data['receiver'], contact_way=self.contact_way)
        if data['receiver__username']:
            user_data = tools.get_receiver_with_username(receiver__username=data['receiver__username'], contact_way=self.contact_way)
            data.update(user_data)
        if self.dest_url:
            result = self.outgoing.http_client.request_by_url('POST', self.dest_url, data=json.dumps(data))
            if result['result'] and data.get('_extra_user_error_msg'):
                result = {'result': False,'message': u'部分用户短信发送失败。%s' % data['_extra_user_error_msg']
                   }
            self.response.payload = result
        else:
            if self.qcloud_app_id and self.qcloud_app_key:
                params = {'sms_type': 0,'phone_numbers': data['receiver'],
                   'content': data['content'],
                   'sdk_app_id': self.qcloud_app_id,
                   'app_key': self.qcloud_app_key
                   }
                result = self.invoke_other('generic.qcloud_sms.send_multi_sms', kwargs=params)
                if result['result'] and data.get('_extra_user_error_msg'):
                    result = {'result': False,'message': u'部分用户短信发送失败。%s' % data['_extra_user_error_msg']
                       }
                self.response.payload = result
            else:
                self.response.payload = {'result': False,'message': u'未完成接口，需要组件负责人进行完善'}
